// 后端基础路径配置
const BASE_URL = "https://127.0.0.1:8086"; // TODO: 后续会改成真实域名

/**
 * 通用网络请求封装
 * @param {String} method 请求方法 GET/POST/PUT/DELETE
 * @param {String} url 接口路径，例如 /api/auth/user-info
 * @param {Object} data 请求参数
 * @param {Boolean} needAuth 是否需要认证，默认false
 * @returns {Promise} 返回处理后的响应数据
 */
function request(method, url, data = {}, needAuth = false) {
	return new Promise((resolve, reject) => {
		// 构建完整URL
		const fullUrl = `${BASE_URL}${url}`;
		
		// 构建请求头
		const header = {
			'Content-Type': 'application/json'
		};
		
		// 如果需要认证，添加token
		if (needAuth) {
			const token = uni.getStorageSync('token');
			if (token) {
				header['Authorization'] = `Bearer ${token}`;
			}
		}
		
		// 发起请求
		uni.request({
			url: fullUrl,
			method: method,
			data: data,
			header: header,
			success: (res) => {
				console.log('API Response:', res);
				
				// 检查HTTP状态码
				if (res.statusCode === 200) {
					const { code, msg, data: responseData } = res.data;
					
					// 检查业务状态码
					if (code === 200) {
						resolve(responseData);
					} else {
						// 业务错误，显示后端返回的错误信息
						uni.showToast({
							title: msg || '请求失败',
							icon: 'none',
							duration: 2000
						});
						reject(new Error(msg || '请求失败'));
					}
				} else {
					// HTTP错误
					uni.showToast({
						title: '网络请求失败',
						icon: 'none',
						duration: 2000
					});
					reject(new Error(`HTTP ${res.statusCode}`));
				}
			},
			fail: (err) => {
				console.error('Request failed:', err);
				uni.showToast({
					title: '网络连接失败',
					icon: 'none',
					duration: 2000
				});
				reject(err);
			}
		});
	});
}

// 便捷方法
const api = {
	get: (url, data, needAuth = false) => request('GET', url, data, needAuth),
	post: (url, data, needAuth = false) => request('POST', url, data, needAuth),
	put: (url, data, needAuth = false) => request('PUT', url, data, needAuth),
	delete: (url, data, needAuth = false) => request('DELETE', url, data, needAuth)
};

export { request, api, BASE_URL };